/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.jittojava.action;

import com.inspur.edp.jittojava.context.entity.MavenDependency;
import com.inspur.edp.jittojava.core.MavenDependencyConst;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * @Classname Utils
 * @Description TODO
 * @Date 2019/12/24 17:20
 * @Created by liu_bintr
 * @Version 1.0
 */
public class Utils {

    public ArrayList<MavenDependency> getExtendDependency() {
        String extendDependencyPath =
            this.getClass().getResource("/CommonExtendMavenDependency.xml").toString();
        return readInternalDependency(extendDependencyPath);
    }

    private ArrayList<MavenDependency> readInternalDependency(String defaultDependencyPath) {
        ArrayList<MavenDependency> result = new ArrayList<>();
        Document doc = readDocument(defaultDependencyPath);
        Element rootElement = doc.getRootElement();
        List<Element> list = rootElement.elements();
        for (int i = 0; i < list.size(); i++) {
            Element ele = (Element) list.get(i);
            result.add(new MavenDependency(getTagValue(ele, MavenDependencyConst.groupId), getTagValue(ele, MavenDependencyConst.artifactId),
                getTagValue(ele, MavenDependencyConst.version), getTagValue(ele, MavenDependencyConst.file)));
        }
        return result;
    }

    private Document readDocument(String filePath) {
        SAXReader sr = new SAXReader();
        try {
            return sr.read(filePath);
        } catch (DocumentException e) {
            throw new RuntimeException("无效路径" + filePath);
        }
    }

    private String getTagValue(Element ele, String tagName) {
        Element tagElement = (Element) ele.element(tagName);
        if (tagElement == null) {
            return null;
        }
        return tagElement.getText();
    }

}
